

package com.yeyks.resolver;

import com.yeyks.account.dal.domain.AccountInfo;
import com.yeyks.annotation.LoginUser;
import com.yeyks.aop.AuthorizationInterceptor;
// import com.yeyks.modules.sys.entity.AccountInfoEntity;
import com.yeyks.commonReference.service.account.AccountInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 有@LoginUser注解的方法参数，注入当前登录用户
 *
 * @author administrator
 */
@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    //private SysUserService sysUserService;
    private AccountInfoService accountInfoService;


    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(AccountInfo.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest nativeWebRequest, WebDataBinderFactory factory) throws Exception {
        //获取用户ID
        Object object = nativeWebRequest.getAttribute(AuthorizationInterceptor.USER_KEY, RequestAttributes.SCOPE_REQUEST);
        if(object == null){
            return null;
        }

        //获取用户信息
        AccountInfo user = accountInfoService.findByPrimaryKey((Integer) object);

        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        request.setAttribute("loginUser",user);

        return user;
    }
}
